package gui.VPOfOperations;

import entities.FailSet;
import entities.ProductionOrder;
import entities.RequestParameters;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableModel;

import net.miginfocom.swing.MigLayout;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;

import table.model.EnvelopeTableModel;
import table.model.renderer.CrossTabRenderer;
import table.model.renderer.NumberRenderer;
import table.model.renderer.SimpleRenderer;
import utilities.PrintActionListener;

import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.Font;

/**
 * @author Idan
 *Report GUI
 */
public class VPOfOperationsFailQuantitiesByReasonReport extends JPanel 
{
	private JPanel mainPanel;
	private JScrollPane chartTableScroll;
	public DefaultTableModel model;
	private DefaultCategoryDataset dataset ;

	private VPOfOperationsTabbedPane tabbedpane;
	private JTable table;
	
	public VPOfOperationsFailQuantitiesByReasonReport(VPOfOperationsTabbedPane myTabbedPane, RequestParameters parameters) 
	{
		setBackground(new Color(173, 216, 230));
		this.tabbedpane = myTabbedPane;
		setLayout(new MigLayout("", "[][grow][]", "[][grow][][]"));
		
		mainPanel = new JPanel(){	@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		mainPanel.setBackground(new Color(173, 216, 230));
		mainPanel.setBorder(new TitledBorder(null, "\u05D3\u05D5\u05D7 \u05E4\u05E1\u05D9\u05DC\u05D5\u05EA \u05DC\u05E4\u05D9 \u05E1\u05D9\u05D1\u05EA \u05E4\u05E1\u05D9\u05DC\u05D4 "  + new Date(parameters.getStartTimestamp().getTime()) + " - " + new Date(parameters.getEndTimestamp().getTime()) , TitledBorder.CENTER, TitledBorder.TOP, null, new Color(59, 59, 59)));
		add(mainPanel, "cell 1 1,growx,aligny center");
		mainPanel.setLayout(new MigLayout("", "[][grow]", "[][::200px][grow]"));
		
		JScrollPane scrollPane = new JScrollPane();
		mainPanel.add(scrollPane, "cell 1 1,alignx center,aligny center");
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 15));
		scrollPane.setViewportView(table);
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
			}
		));
		table.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		
	
		
		JButton closeButton = new JButton("סגור דוח");
		closeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		closeButton.setIcon(new ImageIcon(VPOfOperationsFailQuantitiesByReasonReport.class.getResource("/graphics/back.png")));
		closeButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				// get tab index
				tabbedpane.remove(tabbedpane.getSelectedIndex());
				// remove tab
			}
		});
		add(closeButton, "flowx,cell 1 2,alignx center");
		
		JLabel lblNewLabel = new JLabel("               ");
		add(lblNewLabel, "cell 1 2");
		
		JButton printButton = new JButton("יצא לאקסל");
		printButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		printButton.setIcon(new ImageIcon(VPOfOperationsFailQuantitiesByReasonReport.class.getResource("/graphics/excel.png")));
		printButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) 
			{
//JTable table = utilities.Services.parsePivotTableToJTrable(myTable);
				
				ArrayList<Object> result = utilities.Services.exportToExcel(table);
				if (result.get(0).equals(true))
				{
					// confirm
					JOptionPane.showMessageDialog(mainPanel,
							result.get(1).toString() + " :הדוח נשמר " ,"אישור",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					// error
					JOptionPane.showMessageDialog(mainPanel,
						    "לא ניתן לשמור את הדוח.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				//new Thread(new PrintActionListener(mainPanel)).start();      
			}
		});
		add(printButton, "cell 1 2,alignx center");
		
		
		  
	}
	
	public void setVariables(ArrayList<Object> response) 
	{
		// index 0 is the flag
		// index 1 is the counter
		// index 2 is the product family
		// index 3 and onwards is the data

		
		model = (DefaultTableModel) table.getModel();
		
		int columnCount = ((int)response.get(1));
		String family = response.get(2).toString();
		 

		
		 Object[] columnData = null;
		 
		 if (family.contentEquals("הכל")) // All reasons
		 {
			 for (int i=1; i<=columnCount;i++)
		        {
		        	
		        	FailSet set = (FailSet)response.get(i+2);
		        //    model.addRow(new Object[]{report.getReportSideB(),report.getReportSideA(),report.getEmployee(),report.getEngraveDateAsString(),report.getQuantity(),report.getDiopter(),report.getType(),report.getOrderID()});
		            model.addColumn(set.getProductFamily(), new Object[]{set.getScratches(),
		            	set.getStuckChip(), set.getEngraveMarks(), set.getAoptic(),
		            	set.getDiopterDeviation(), set.getSurface(), set.getDirt(),
		            	set.getDropedOrLost(), set.getBumps(), set.getHydration(),
		            	set.getLoops(), set.getFractures(), set.getMilling(),
		            	set.getAsymmetry(), set.getCharacteristics(), set.getOrange(),
		            	set.getC1TurnLens(), set.getC2ChippedEdge(), set.getC3CuttingChips(),
		            	set.getC4Scratches(), set.getC5Prism(), set.getC6FoldedLens(),
		            	set.getC7OODDiameter(), set.getC8OODThickness(), set.getC9Lost(),
		            	set.getC10LatheMarks(), set.getC11ChippedHole(), set.getC12NoHole(),
		            	set.getC13UndefinedParticles(), set.getC14FoggyResolution(),
		            	set.getC15OODDiopterPower(), set.getC16OODPlanoPower(),
		            	set.getEngravingStationEngraving(), set.getEngravingStationCharacteristics(),
		            	set.getEngravingStationDroppedOrLost(), set.getDryFails()  	});		
		        }
			 
			columnData=new Object[]{"שריטות",
						"שבב דבוק","סימני חריטה","א.אופטית","סטייה בדיופטר","פני שטח",
						"ליכלוך","נפל או אבד","בליטות","הידרציה","לולאות","שברים","כרסום",
						"אסימטריה","מידות","פני תפוז",
						"C1 - Turn Lens","C2 - Chipped Edge","C3 - Cutting Chips","C4 - Scratch","C5 - Prism(Asymmetric Lens)","C6 - Folded Lens","C7 - OOD -Diameter","C8 - OOD-Thickness",
						"C9 - Lost Lens","C10 - Lathe Marks","C11 - Chipped Hole","C12 - No Hole","C13 - Undefined Particles","C14 - Foggy Resolution","C15 - OOD – Diopter Power","C16 - OOD – Plano Power",
						"ייצור - חריטה","ייצור - מידות","ייצור- נפל או אבד","פסילה ביבש"};
		 }
		 else
		 {
			 if (family.equalsIgnoreCase("פרסביה")) // Just Presbia
			 {
				 
     	
			        	FailSet set = (FailSet)response.get(3);
			        //    model.addRow(new Object[]{report.getReportSideB(),report.getReportSideA(),report.getEmployee(),report.getEngraveDateAsString(),report.getQuantity(),report.getDiopter(),report.getType(),report.getOrderID()});
			            model.addColumn(set.getProductFamily(), new Object[]{
			            	set.getC1TurnLens(), set.getC2ChippedEdge(), set.getC3CuttingChips(),
			            	set.getC4Scratches(), set.getC5Prism(), set.getC6FoldedLens(),
			            	set.getC7OODDiameter(), set.getC8OODThickness(), set.getC9Lost(),
			            	set.getC10LatheMarks(), set.getC11ChippedHole(), set.getC12NoHole(),
			            	set.getC13UndefinedParticles(), set.getC14FoggyResolution(),
			            	set.getC15OODDiopterPower(), set.getC16OODPlanoPower(), set.getDryFails()  	});		
			        
				 
				 columnData=new Object[]{
						 "C1 - Turn Lens","C2 - Chipped Edge","C3 - Cutting Chips","C4 - Scratch","C5 - Prism(Asymmetric Lens)","C6 - Folded Lens","C7 - OOD -Diameter","C8 - OOD-Thickness",
							"C9 - Lost Lens","C10 - Lathe Marks","C11 - Chipped Hole","C12 - No Hole","C13 - Undefined Particles","C14 - Foggy Resolution","C15 - OOD – Diopter Power","C16 - OOD – Plano Power",
							"פסילה ביבש"};
							
				 
			 }
			 else // All but Presbia
			 {
				 
				 for (int i=1; i<=columnCount;i++)
			        {
			        	
			        	FailSet set = (FailSet)response.get(i+2);
			        //    model.addRow(new Object[]{report.getReportSideB(),report.getReportSideA(),report.getEmployee(),report.getEngraveDateAsString(),report.getQuantity(),report.getDiopter(),report.getType(),report.getOrderID()});
			            model.addColumn(set.getProductFamily(), new Object[]{set.getScratches(),
			            	set.getStuckChip(), set.getEngraveMarks(), set.getAoptic(),
			            	set.getDiopterDeviation(), set.getSurface(), set.getDirt(),
			            	set.getDropedOrLost(), set.getBumps(), set.getHydration(),
			            	set.getLoops(), set.getFractures(), set.getMilling(),
			            	set.getAsymmetry(), set.getCharacteristics(), set.getOrange(),
			            	set.getEngravingStationEngraving(), set.getEngravingStationCharacteristics(),
			            	set.getEngravingStationDroppedOrLost()  	});		
			        }
				 
				 columnData=new Object[]{"שריטות",
							"שבב דבוק","סימני חריטה","א.אופטית","סטייה בדיופטר","פני שטח",
							"ליכלוך","נפל או אבד","בליטות","הידרציה","לולאות","שברים","כרסום",
							"אסימטריה","מידות","פני תפוז",
							"ייצור - חריטה","ייצור - מידות","ייצור- נפל או אבד"};
			 }
		 }
			
			model.addColumn("סיבת פסילה", columnData);	
		
			
			table.getColumnModel().getColumn(table.getColumnCount()-1).setPreferredWidth(210);
			
			int rowCount = columnData.length;
			
		
		        // initialize Dataset
		        
		        dataset = new DefaultCategoryDataset();
		        
		        for (int rowStart=0; rowStart<rowCount;rowStart++)
		        {
		        	for (int colStart=0 ;colStart<columnCount ;colStart++)
		        	{
		        		// pivotTable might return null when there's no value

		        		 Number count = Integer.parseInt(model.getValueAt(rowStart, colStart).toString());	        		
		        		String productFamily = model.getColumnName(colStart);
		        		String reason = model.getValueAt(rowStart, columnCount).toString();
		        	//	System.out.println("Count = " + count + " productFamily = " + productFamily + " reason = " + reason);		        		
		        		
		        		dataset.addValue(count,productFamily,reason);
		        		
		        		
		        		
		        	}
		        	
		        }
		        
		        

		        // create Chart
		        
		      
		      //  JFreeChart chart = ChartFactory.createBarChart(
		        JFreeChart chart = ChartFactory.createStackedBarChart3D(
		        		((TitledBorder)mainPanel.getBorder()).getTitle(), // chart title
		        		"סיבת פסילה", // domain axis label
		        		"פסילות", // range axis label
		        		dataset, // data
		        		PlotOrientation.VERTICAL, // orientation
		        		true, // include legend
		        		true, // tooltips?
		        		false // URLs?
		        		);

		        
		    
		        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
		      //  plot.setRenderer(new StackedBarRenderer3D(true));
		        BarRenderer renderer =  (BarRenderer) plot.getRenderer();
		        DecimalFormat format = new DecimalFormat("##.#");
		        renderer.setItemLabelGenerator((CategoryItemLabelGenerator) new StandardCategoryItemLabelGenerator("{2}",format));
		        renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_CENTER));
		        renderer.setItemLabelsVisible(true);
		        
		        
		        CategoryAxis xAxis = (CategoryAxis)plot.getDomainAxis();
		        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
		        
//		        renderer.setSeriesItemLabelsVisible(0, true);

		        //renderer.
		        // renderer.setItemMargin(0.0);
		        
		        
		        ChartPanel chartPanel = new ChartPanel(chart, false);
		        chartPanel.setMouseWheelEnabled(true);
		      //  chartPanel.setPreferredSize(new Dimension(500, 270));
		        
		        chartTableScroll = new JScrollPane(chartPanel);
		        mainPanel.add(chartTableScroll, "cell 1 2,grow");
		       // mainPanel.add(chartPanel, "cell 1 2,grow");
		       // chartPanel.setVisible(true);
		        

		
		
	}

	

	
	
	 public TableModel getModel(ArrayList<Object> response)
	 {
		 
	        Object[][] ss=new Object[response.size()-2][4];
	       
	        
	        for (int i=1; i<=((int)response.get(1));i++)
	        {
	        	
	        	ProductionOrder report = (ProductionOrder)response.get(i+1);
	        	ss[i-1] = new Object[]{report.getQuantity(),Integer.parseInt(report.getFails()),report.getDiopter(),report.getType(),report.getProductFamily(),report.getOrderID()};
	        }
	        
	       
	        FailQuantitiesReportTable dm= new FailQuantitiesReportTable(ss,new String[] {"Quantity","Fails","Diopter","Type","ProductFamily","OrderID"});
	        return dm;
	    }
	 
	 
		@Override
		public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Color color1 = getBackground();
        Color color2 = color1.darker();
        int w = getWidth();
        int h = getHeight(); 
        GradientPaint gp = new GradientPaint(
                0, 0, color1,
                0, h, color2);

        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        }
	 
	 
}